var marked = require('marked');

const glob = require('glob')
const fs = require('fs');
const path = require('path');

var phantom = require('phantom');

marked.setOptions({
    renderer: new marked.Renderer(),
    gfm: true,
    tables: true,
    breaks: false,
    pedantic: false,
    sanitize: false,
    smartLists: true,
    smartypants: false
});
const dir = process.cwd() + '\\src\\js\\md'

async function main() {
  function renderHTML() {
    return new Promise((resolve, reject) => {
      glob('*.md', {
        cwd: dir,
        nodir: true
      }, (err, files) => {
        if(err) {
          reject(err)
        }
        if(files) {
            const promises = files.map((file, idx) => {
              const filePath = path.join(dir, file)
              return async function()  {
                const fileName = fs.readFileSync(filePath, 'utf-8')
                const html = marked(fileName)
                const style = `<style>
  body {
    width: 100%;
    padding-top: 80px;
  }
  h1, h2, h3, h4, h5, h6, ul, ol, pre,  p, img{
    width: 794px;
    margin: 0 auto;
  }
  p {
    white-space: pre-wrap;
  }
</style>`
                if(html) {
                  const reg =  /] (.*)\./g
                  const name = dir + '\\' + filePath.match(reg)[0].slice(2)
                  await writeFile(dir + `\\index${idx}.html`, html + style)
                  const instance = await phantom.create();
                  const page = await instance.createPage();
                  page.paperSize = { format: 'A4', orientation: 'portrait', margin: '0.8cm' };
                  await page.on('onResourceRequested', function(requestData) {
                    console.info('请求资源中', requestData.url);
                  });
                  await page.open(`http://localhost:3000/index${idx}.html`);
                  await page.render(`${name}.pdf`)
                  fs.rmSync(dir + `\\index${idx}.html`)
                  fs.rmSync(filePath)
                  console.log(name, '页面转换成功！');
                  await instance.exit();
                }
              }
            })
            promises.forEach(async fn => {
              await fn()
            })
        }
      })
    })
  }
  await renderHTML()
}

function writeFile(path, data, { rewrite = true } = {}) {
  if(fs.existsSync(path)) {
      if(rewrite) {
          fs.writeFileSync(path, data)
          return true
      }
      return false
  } else {
      fs.writeFileSync(path, data)
      return true
  }
}

main()

